package threadPractise.chapter3;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class IntLock implements Runnable {
    public static ReentrantLock lock1 = new ReentrantLock();
    public static ReentrantLock lock2 = new ReentrantLock();
    Condition c =lock1.newCondition();
    int lock;

    public IntLock(int lock) {
        this.lock = lock;
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getId() + ":开始");
        try {
            if (lock == 1) {
                lock1.lockInterruptibly();
                try {
                    System.out.println(Thread.currentThread().getId() + ":等等");
                    Thread.sleep(5000);
                    System.out.println(Thread.currentThread().getId() + ":等等结束");
                } catch (InterruptedException e) {
                }
                System.out.println(Thread.currentThread().getId() + ":锁2获取");
                lock2.lockInterruptibly();
                System.out.println(Thread.currentThread().getId() + ":锁2获取成功");
            } else {
                lock2.lockInterruptibly();
                try {
                    System.out.println(Thread.currentThread().getId() + ":等等");
                    Thread.sleep(5000);
                    System.out.println(Thread.currentThread().getId() + ":等等结束2");
                } catch (InterruptedException e) {
                    System.out.println(Thread.currentThread().getId() + ":发生中断");
                    if (lock2.isHeldByCurrentThread()) {
                        lock2.unlock();
                        System.out.println(Thread.currentThread().getId() + ":线程释放锁2");
                    }
                }
                lock1.lockInterruptibly();
            }
        } catch (InterruptedException e) {
            System.out.println(Thread.currentThread().getId() + ":中断");
        } finally {
            if (lock1.isHeldByCurrentThread()) {
                lock1.unlock();
                System.out.println(Thread.currentThread().getId() + ":线程释放锁1");
            }
            if (lock2.isHeldByCurrentThread()) {
                lock2.unlock();
                System.out.println(Thread.currentThread().getId() + ":线程释放锁2");
            }
            System.out.println(Thread.currentThread().getId() + ":线程退出");
        }

    }

    public static void main(String[] args) throws InterruptedException {
        IntLock r1 = new IntLock(1);
        IntLock r2 = new IntLock(2);
        Thread t1 = new Thread(r1);
        Thread t2 = new Thread(r2);
        t1.start();
        t2.start();
        Thread.sleep(1000);
        t2.interrupt();
    }

}
